package com.zdp.rocketmq.send.order;

import com.zdp.rocketmq.config.JmsConfig;
import com.zdp.rocketmq.domain.ProducerOrder;
import com.zdp.rocketmq.producer.ProducerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author sesshomaru
 * @date 2021/6/21
 * 顺序消息发送方
 */
@Slf4j
@RestController
public class OrderController {

    @Autowired
    private ProducerBuilder producerBuilder;

    @RequestMapping("/api/v1/order")
    public Object send() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        List<ProducerOrder> orderList = ProducerOrder.getOrderList();
        for (int i = 0 ; i < orderList.size() ; i++) {
            ProducerOrder order = orderList.get(i);
            Message message = new Message(JmsConfig.ORDER_TOPIC, "", order.getClass() + "", order.toString().getBytes());
            SendResult sendResult = producerBuilder.getProducer().send(message, new MessageQueueSelector() {
                // list 就是队列   message 消息  o 附带参数
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    //o 就是 order.getOrderId() 获得订单号将将 消息中有着相同订单号的消息放到同一个队列下
                    Long orderId = (Long) o;
                    long index = orderId % list.size();
                    //这里控制去发送到哪个队列
                    return list.get((int) index);
                }
                //同一个订单id的消息会进入同一个队列里面去
            }, order.getOrderId());
            log.info("发送结果={},msg={},orderId={},type={}", sendResult.getSendStatus(),sendResult.toString(),order.getOrderId(),order.getType());
        }
        return new HashMap<>(1);
    }
}
